package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.Question;
import com.company.aicrawlers.entity.QuestionCategory;
import com.company.aicrawlers.mapper.QuestionCategoryMapper;
import com.company.aicrawlers.mapper.QuestionMapper;
import com.company.aicrawlers.service.QuestionCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 问句-类别关联服务实现类
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@Service
public class QuestionCategoryServiceImpl implements QuestionCategoryService {
    
    @Autowired
    private QuestionCategoryMapper questionCategoryMapper;
    
    @Autowired
    private QuestionMapper questionMapper;
    
    @Override
    public List<String> getCategoryNamesByQuestionId(Long questionId) {
        List<String> categoryNames = questionCategoryMapper.selectCategoryNamesByQuestionId(questionId);
        log.info("获取问句关联类别，问句ID: {}, 类别数: {}", questionId, categoryNames.size());
        return categoryNames;
    }
    
    @Override
    public List<Long> getQuestionIdsByCategoryName(String categoryName) {
        List<Long> questionIds = questionCategoryMapper.selectQuestionIdsByCategoryName(categoryName);
        log.info("获取类别关联问句，类别名称: {}, 问句数: {}", categoryName, questionIds.size());
        return questionIds;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addRelation(Long questionId, Long categoryId, String categoryName, Integer sortOrder) {
        // 验证问句是否存在
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new BusinessException("问句不存在");
        }
        
        // 检查关联是否已存在
        LambdaQueryWrapper<QuestionCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionCategory::getQuestionId, questionId)
               .eq(QuestionCategory::getCategoryId, categoryId);
        
        QuestionCategory exist = questionCategoryMapper.selectOne(wrapper);
        if (exist != null) {
            throw new BusinessException("该关联已存在");
        }
        
        // 创建关联
        QuestionCategory relation = new QuestionCategory();
        relation.setQuestionId(questionId);
        relation.setCategoryId(categoryId);
        relation.setCategoryName(categoryName);
        relation.setSortOrder(sortOrder == null ? 0 : sortOrder);
        relation.setCreateTime(LocalDateTime.now());
        
        questionCategoryMapper.insert(relation);
        log.info("添加问句-类别关联成功，问句ID: {}, 类别ID: {}", questionId, categoryId);
        
        return relation.getId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeRelation(Long questionId, Long categoryId) {
        LambdaQueryWrapper<QuestionCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionCategory::getQuestionId, questionId)
               .eq(QuestionCategory::getCategoryId, categoryId);
        
        int count = questionCategoryMapper.delete(wrapper);
        if (count == 0) {
            throw new BusinessException("关联不存在");
        }
        
        log.info("移除问句-类别关联成功，问句ID: {}, 类别ID: {}", questionId, categoryId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSetRelations(Long questionId, List<QuestionCategory> relations) {
        // 验证问句是否存在
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new BusinessException("问句不存在");
        }
        
        // 先清除旧关联
        clearQuestionRelations(questionId);
        
        // 添加新关联
        if (relations != null && !relations.isEmpty()) {
            for (QuestionCategory relation : relations) {
                relation.setQuestionId(questionId);
                relation.setCreateTime(LocalDateTime.now());
                questionCategoryMapper.insert(relation);
            }
        }
        
        log.info("批量设置问句类别关联成功，问句ID: {}, 关联数: {}", questionId, relations == null ? 0 : relations.size());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearQuestionRelations(Long questionId) {
        LambdaQueryWrapper<QuestionCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionCategory::getQuestionId, questionId);
        
        questionCategoryMapper.delete(wrapper);
        log.info("清除问句的所有类别关联，问句ID: {}", questionId);
    }
}

